import numpy as np


def SpDtw(X, Y):
    m = len(X) - 1
    n = len(Y) - 1
    x = np.zeros([1, m])
    y = np.zeros([1, n])

    for i in range(m):
        x[i] = X(i + 1) - X(i)

    for j in range(n):
        y[j] = Y(j + 1) - Y(j)

    total = (abs(x[1] - y[1])) / 1000
    t = j = i = 0

    while i < m and j < n:
        d1 = (abs(x[i] - y[j + 1])) / 1000
        d2 = (abs(x[i + 1] - y[j])) / 1000
        d3 = (abs(x[i + 1] - y[j + 1])) / 1000
        k = min(d1, d2)
        k = min(k, d3)
        total = total + k
        t = t + 1
        if k == d1:
            i = i
            j = j + 1

        if k == d2:
            i = i + 1
            j = j

        if k == d3:
            i = i + 1
            j = j + 1

    if i == m and j == n:
        total = total / t

    if i == m and j < n:
        for ll in range(j, n):
            total = total + (abs(x[m] - y[ll + 1])) / 1000
        t = t + n - j
        total = total / t

    if i < m and j == n:
        for ll in range(i, m):
            total = total + (abs(x[ll + 1] - y[n])) / 1000
        t = t + m - i
        total = total / t

    return total
